export function polyfillHiDPI(canvas: HTMLCanvasElement, width: number, height: number): CanvasRenderingContext2D{
    const devicePixelRatio = window.devicePixelRatio || 1;
    
    canvas.width = width * devicePixelRatio;
    canvas.height = height * devicePixelRatio;
    
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';

    const ctx = canvas.getContext('2d');
    ctx.scale(devicePixelRatio, devicePixelRatio);
    return ctx;
}

export function drawRuler(vertical, ctx, start, width, height, canvasConfigs) {
    const {bgColor, fontColor, shortMarkColor, longMarkColor} = canvasConfigs;

    const DIVISION_BASIS = 10;
    const minimumMarkPixel = DIVISION_BASIS; // 最小刻度像素值
    const mediumMarkPixel = DIVISION_BASIS * 10; // 中等刻度像素值（1中等刻度 = 10最小刻度）

    const startMinimumMark = Math.floor(start / minimumMarkPixel) * minimumMarkPixel;  // 绘制起点的刻度(略小于start, 且是gridSize的整数倍)
    const startMediumMark = Math.floor(start / mediumMarkPixel) * mediumMarkPixel;  // 长间隔绘制起点的刻度(略小于start, 且是gridSize_10的整数倍)
    const end = start + vertical ? Math.ceil(height) : Math.ceil(width);               // 终点刻度(略超出标尺宽度即可)

    ctx.font = `12px -apple-system, "Helvetica Neue", ".SFNSText-Regular", "SF UI Text", Arial, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Zen Hei", sans-serif`;
    ctx.textBaseline = "top";

    // clear
    ctx.clearRect(0, 0, width, height);

    // 绘制底色
    ctx.fillStyle = bgColor;
    ctx.fillRect(0, 0, width, height);

    // 绘制长刻度+文字
    ctx.beginPath();
    ctx.fillStyle = fontColor;
    ctx.strokeStyle = longMarkColor;
    for (let i = startMediumMark, count = 0; i < end; i += mediumMarkPixel, count++) {
        if (vertical) {
            ctx.save();
            ctx.translate(0, i);
            ctx.rotate(-Math.PI / 2);
            ctx.fillText(i + "", 0, 0);
            ctx.restore();

            ctx.moveTo(0, i+0.5);
            ctx.lineTo(width, i+0.5);
        } else {
            ctx.save();
            ctx.translate(i, 0);
            ctx.fillText(i + "", 0, 0);
            ctx.restore();

            ctx.moveTo(i+0.5, 0);
            ctx.lineTo(i+0.5, height);
        }
    }
    ctx.stroke();
    ctx.closePath();

    // 绘制短刻度
    ctx.beginPath();
    ctx.strokeStyle = shortMarkColor;
    for (let i = startMinimumMark, count = 0; i < end; i += minimumMarkPixel, count++) {
        if (i % mediumMarkPixel !== 0) {
            if (vertical) {
                ctx.moveTo(width * 3 / 4, i+0.5);
                ctx.lineTo(width, i+0.5);
            } else {
                ctx.moveTo(i+0.5, height * 3 / 4);
                ctx.lineTo(i+0.5, height);
            }
        }

    }
    ctx.stroke();
    ctx.closePath();
}
